from datetime import datetime
from fastapi import APIRouter, HTTPException, Response
from email_validate import validate
from utils.auth import pwd_context, create_jwt_token, EXPIRATION_TIME
from api.dep import uow_dep
from api.schemas import RegisterUserInfo

router = APIRouter(prefix="/auth", tags=['auth'])


@router.post("/reg/")
async def reg(info: RegisterUserInfo, uow=uow_dep):
    if not validate(info.email):
        raise HTTPException(status_code=400,
                            detail="Неправильный email")

    if await uow.users.select_by_email(info.email) is not None:
        raise HTTPException(status_code=400,
                            detail="Человек с данным email уже существует")

    await uow.users.insert(info.email, info.password)

    return "ok"


@router.post("/auth/")
async def auth(response: Response, info: RegisterUserInfo, uow=uow_dep):
    user = await uow.users.select_by_email(info.email)

    if user is None:
        raise HTTPException(status_code=400,
                            detail="Несуществующий email или пароль")

    if not pwd_context.verify(info.password, user.password):
        raise HTTPException(status_code=400,
                            detail="Несуществующий email или пароль")

    token = create_jwt_token({"id": user.id})
    max_age = datetime.now() + EXPIRATION_TIME
    response.set_cookie("token", token, max_age=max_age)

    return {"token": token}
